package com.tq.auth.client;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * HTTP 调试日志工具类
 * 统一格式化输出请求与响应信息，方便排查问题
 *
 * @author TqCoder
 * @since 2.0.0
 */
@Slf4j
public class HttpDebugUtils {

    /**
     * 打印 HTTP 请求信息
     *
     * @param method  请求方法
     * @param url     请求地址
     * @param headers 请求头（可选）
     * @param body    请求体（可选）
     */
    public static void logRequest(String method, String url, Map<String, String> headers, Object body) {
        log.info("==================== Request Start ===================================================================");
        log.info("Method: {}", method);
        log.info("URL: {}", url);
        if (headers != null && !headers.isEmpty()) {
            headers.forEach((key, value) -> log.info("Header: {} = {}", key, value));
        }
        if (body != null) {
            log.info("Body: {}", body instanceof String ? body : JSONUtil.toJsonStr(body));
        }
        log.info("==================== Request End =====================================================================");
    }

    /**
     * 打印 HTTP 响应（包含 body）
     */
    public static void logResponse(HttpResponse response) {
        logResponse(response, true);
    }

    /**
     * 打印 HTTP 响应
     *
     * @param response 响应对象
     * @param logBody  是否打印响应体
     */
    public static void logResponse(HttpResponse response, boolean logBody) {
        log.info("==================== Response Start ==================================================================");
        log.info("Status: {}", response.getStatus());
        response.headers().forEach((key, value) -> log.info("{}: {}", key, value));
        if (logBody) {
            log.info("{}", response.body());
        }
        log.info("==================== Response End ====================================================================\n");
    }

    /**
     * 发送 POST 表单并记录请求和响应
     */
    public static HttpResponse postForm(String url, Map<String, Object> form, Map<String, String> headers) {
        logRequest("POST", url, headers, form);
        HttpRequest req = HttpRequest.post(url).form(form);
        if (headers != null) {
            headers.forEach(req::header);
        }
        HttpResponse resp = req.execute();
        logResponse(resp);
        return resp;
    }

    /**
     * 发送 GET 请求并记录请求和响应
     */
    public static HttpResponse get(String url, Map<String, String> headers) {
        logRequest("GET", url, headers, null);
        HttpRequest req = HttpRequest.get(url);
        if (headers != null) {
            headers.forEach(req::header);
        }
        HttpResponse resp = req.execute();
        logResponse(resp);
        return resp;
    }
}
